<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Ajax取消请求</title>
    <style>
      #result {
        width: 200px;
        height: 100px;
        border: solid 1px pink;
      }
    </style>
    
  </head>
  <body>
    <button>点击发送请求</button>
    <button>点击取消请求</button>
    <div id="result"></div>
  </body>
  <script type="text/javascript">
    const btn = document.getElementsByTagName('button')[0]
    const btn2 = document.getElementsByTagName('button')[1]
    const result = document.getElementById('result')
    var isSending = false
    var xhr = new XMLHttpRequest();
    btn.onclick = function(){
        if (isSending) xhr.abort();
        console.log('执行了')
        xhr.open('GET','http://127.0.0.1:8000/delay')
        xhr.send();
        isSending=true
        xhr.onreadystatechange = function(){
            //判断
            if(xhr.readyState ===4){
                //判断响应状态码
                if(xhr.status>=200&&xhr.status<300){
                    //处理结果
                    console.log(xhr.status);
                    console.log(xhr.statusText);
                    console.log(xhr.getResponseHeader);//所有响应头
                    console.log(xhr.response)//响应体
                    result.innerText=xhr.response
                }
            }
            isSending=false
        }
    }
    btn2.onclick = function(){
      xhr.abort()
    }
  </script>
</html>
